package com.chuyunjian.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SerialNumberUtil {
    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private RedisParameter redisParameter;
    /**
     * 生成流水号
     * @param bizCode 流水号前缀（test)
     * @param spliceChar 拼接字符，默认拼接0
     * @param length 长度(4)
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return  test0001
     */
    public String generate(String bizCode,String spliceChar,int length,int delta,long time) {
        String key = redisParameter.getPerKey()+":serialNumber:" + bizCode;
        Object o = redisUtil.get(key);
        if(o==null){
            redisUtil.set(key,0,time);
        }
//        //默认锁2s,避免重复
//        redisUtil.lock(key,"2");
        //** 自增 *//*
        long sequence = redisUtil.incr(key,delta);
        String seq = getSequence(spliceChar,sequence,length);
        StringBuilder sb = new StringBuilder();
        sb.append(bizCode).append(seq);
        String serial = sb.toString();
        return serial;
    }

    /**
     * 自动拼接
     * @param spliceChar 拼接字符，默认拼接0
     * @param seq 流水号
     * @param length 长度
     * @return
     */
    public static String getSequence(String spliceChar,long seq,int length) {
        String str = String.valueOf(seq);
        int len = str.length();
        if (len >= length) {// 取决于业务规模
            return str;
        }
        int rest = length - len;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rest; i++) {
            sb.append(spliceChar==null?'0':spliceChar);
        }
        sb.append(str);
        return sb.toString();
    }
}
